// 通过vue-router创建路由
import useUserstate from "../store/modules/user";
import { createRouter, createWebHashHistory } from "vue-router";
import { constantRouterMap } from "./router";

// 创建路由器
let router = createRouter({
  history: createWebHashHistory(),
  routes: constantRouterMap,
  // scrollBehavior滚动行为
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
});

// 检查路由是否存在
function hasRoute(routes: RouteRecordRaw[], path: string): boolean {
  for (const route of routes) {
    if (route.path === path || (route.children && hasRoute(route.children, path))) {
      return true;
    }
  }
  return false;
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  if (to.path === "/login") {
    next();
  } else {
    const user = useUserstate(); // 合并 useUserstate 调用
    try {
      // 获取菜单
      if (user.token && user.DtmenuRouter.length === 0) {
        const menu = await user.get_UserMenu(); // 使用 async/await 处理异步操作
        const processedMenu = pushRouter(menu.data);
        console.log(processedMenu, "333");
        processedMenu.forEach((route) => {
          if (!hasRoute(router.getRoutes(), route.path)) {
            router.addRoute(route);
          }
        });
        user.DtmenuRouter = processedMenu;
        console.log(user.DtmenuRouter, "443334");
        next();
      } else {
        next(); // 确保 next 总是被调用
      }
    } catch (err) {
      console.error("Error fetching user menu:", err); // 改进异常处理
      next(); // 确保 next 总是被调用
    }
  }
});

interface RouterItem {
  path: string;
  name: string;
  component: any;
  children?: RouterItem[];
  meta: {
    title: string;
    icon: string;
    hidden: boolean;
  };
}

// 动态处理路由
function pushRouter(routes: RouterItem[], parentRoute?: any[]): RouterItem[] {
  const result: RouterItem[] = [];
  routes.forEach((item) => {
    const route: RouterItem = {
      path: item.path,
      name: item.name,
      component: () => import(`@/views/${item.component}.vue`).catch(err => {
        console.error(`Failed to load component ${item.component}:`, err);
        return null; // 或者返回一个默认组件
      }),
      meta: {
        title: item.name,
        icon: item.icon,
        hidden: item.hidden ?? false, // 动态设置 hidden 属性，默认为 false
      },
    };

    if (item.children && item.children.length > 0) {
      route.children = pushRouter(item.children); // 递归调用并将子路由添加到当前路由的 children 中
    }

    if (parentRoute) {
      parentRoute.push(route); // 将当前路由添加到父路由中
    } else {
      result.push(route); // 如果是顶层路由，直接添加到结果数组中
    }
  });
  return result; // 返回处理后的路由数组
}

export default router;
